package main

import (
	"database/sql"
	"fmt"
	_ "github.com/Go-SQL-Driver/MySQL"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"finance/historyImport"
	"finance/timer"
	"time"
)

//var db = make(map[string]string)
var db2 = make(map[string]string)

var db *sql.DB

type Person struct {
	Id   int    `json:"id" form:"id"`
	Name string `json:"name" form:"name"`
	Tel  string `json:"tel" form:"tel"`
}

func setupRouter() *gin.Engine {
	// Disable Console Color
	// gin.DisableConsoleColor()
	router := gin.Default()

	/*	//增加一条记录
		r.POST("/add", func(c *gin.Context) {

			c.JSON(http.StatusOK, gin.H{
				"msg": "",
			})
		})

		// Ping test
		r.GET("/ping/:test/:test1", func(c *gin.Context) {

			//c.String(http.StatusOK, "pong")
			firstName := c.Params.ByName("test")
			lastName := c.Params.ByName("test1")

			rs, err := db.Exec("INSERT INTO test(test, test1) VALUES (?, ?)", firstName, lastName)
			if err := db.Ping(); err != nil {
				log.Fatalln(err)
			} else {
				fmt.Println("Ping status: OK")
			}
			id, err := rs.LastInsertId()
			if err != nil {
				log.Fatalln(err)
			}
			fmt.Println("insert person Id {}", id)
			msg := fmt.Sprintf("insert successful %d", id)
			c.JSON(http.StatusOK, gin.H{
				"msg": msg,
			})

		})
		r.GET("/p", func(c *gin.Context) {
			rows, err := db.Query("SELECT id, name,tel FROM test")

			if err != nil {
				log.Fatalln(err)
			}
			defer rows.Close()

			persons := make([]Person, 0)

			for rows.Next() {
				var person Person
				rows.Scan(&person.Id, &person.Name, &person.Tel)
				persons = append(persons, person)
			}
			if err = rows.Err(); err != nil {
				log.Fatalln(err)
			}

			c.JSON(http.StatusOK, gin.H{
				"persons": persons,
			})

		})*/

	// Get user value
	/*	r.GET("/user/:name", func(c *gin.Context) {

		db2["tian"] = "tian"
		user := c.Params.ByName("name")
		value, ok := db2[user]
		if ok {
			c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
		} else {
			c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})
		}
	})*/

	// Authorized group (uses gin.BasicAuth() middleware)
	// Same than:
	// authorized := r.Group("/")
	// authorized.Use(gin.BasicAuth(gin.Credentials{
	//	  "foo":  "bar",
	//	  "manu": "123",
	//}))
	/*	authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
			"foo":  "bar", // user:foo password:bar
			"manu": "123", // user:manu password:123
		}))

		authorized.POST("admin", func(c *gin.Context) {
			user := c.MustGet(gin.AuthUserKey).(string)

			// Parse JSON
			var json struct {
				Value string `json:"value" binding:"required"`
			}

			if c.Bind(&json) == nil {
				db2[user] = json.Value
				c.JSON(http.StatusOK, gin.H{"status": "ok"})
			}
		})

		return r*/
	router.GET("/history/:code/:starttime/:endtime", func(c *gin.Context) {

		code := c.Params.ByName("code")
		starttime := c.Params.ByName("starttime")
		endtime := c.Params.ByName("endtime")
		insertCount, failCount := historyImport.ImportHistory(code, starttime, endtime)

		//	c.String(http.StatusOK, "Hello %s %s", insertCount,failCount)

		var dataMap map[string]int64 = map[string]int64{}
		dataMap["insertCount"] = insertCount
		dataMap["failCount"] = failCount

		c.JSON(http.StatusOK, gin.H{
			"status": 200,
			"error":  nil,
			"data":   dataMap,
		})
	})

	return router
}

func init() {

/*	//初始化数据库连接池
	db, _ = sql.Open("mysql", "root:leaniot@tcp(mysql:3306)/leaniot?parseTime=true")
	db.SetMaxOpenConns(200)
	db.SetMaxIdleConns(5)
	err := db.Ping()
	if err != nil {
		log.Fatalln("DB PING: ", err)
	}*/
	timer.TimerImportHistory()
}

func main() {
	//导入历史数据

	r := setupRouter()
	// Listen and Server in 0.0".0.0:8080
	r.Run(":8080")


	// 一天前



	fmt.Println(time.Now().String()[0:10])
	fmt.Println(strings.Replace(time.Now().String()[0:10],"-","",-1))

}
